package test.study.concurrent.thread._8_mdc;

import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import java.util.Map;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;

@Slf4j
public class MdcRunnable implements Runnable {

    /* 任务 */
    private final Runnable task;
    /* MDC 上下文 MAP */
    private final Map<String, String> contextMap;

    public MdcRunnable(Runnable task) {
        this.task = task;
        //获取父线程MDC中的内容，必须在run方法之前，
        //否则等异步线程执行的时候有可能MDC里面的值已经被清空了，这个时候就会返回null
        this.contextMap = MDC.getCopyOfContextMap();
        log.info("ssssssssssssssssssssssssss");
    }

    @Override
    public void run() {
        //将父线程的MDC内容传给子线程
        MDC.setContextMap(contextMap);
        try {
            //执行异步操作
            task.run();
        } finally {
            //清空MDC内容
            MDC.clear();
        }
    }

    public static void main(String[] args) {

        ForkJoinPool pool = new ForkJoinPool(100);

        MDC.put("trace_id", "666666");
        log.info(">>>>>> main thread");
        pool.execute(new MdcRunnable(new Runnable() {
            @Override
            public void run() {
                log.info(">>>>>> other thread");
                log.info(">>>>>> other thread");
                log.info(">>>>>> other thread");
            }
        }));

        ThreadUtil.sleep(3, TimeUnit.SECONDS);
    }
}
